﻿using Newtonsoft.Json;
using shuatibao.Constance;
using shuatibao.Tool;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace shuatibao.Web.Account
{
    /// <summary>
    /// AuthLogin 的摘要说明
    /// </summary>
    public class AuthLogin : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string requestJson = new StreamReader(context.Request.InputStream).ReadToEnd();

            Dictionary<string, string> parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(requestJson);

            string code = parameters["code"].ToString();

            // 2. 
            WechatJSCode2SessionModel sessionModel = WechatTool.getcode2SessionManager(code);
            if (sessionModel.unionid != null)
            {
                sessionModel.main_union_id = ConstanceWechat.smartMainUnionId(sessionModel.unionid);
            }

            if (sessionModel.openid != null && sessionModel.openid != "")
            {
                // 1. 判断是否存在
                WechatUserModel userInfo = AccountAction.getUserInfoWithUnionId(sessionModel.unionid);
                if (userInfo.id == null)
                {
                    AccountAction.createUserManagerWithXCX(sessionModel.unionid, sessionModel.openid);
                }
                else
                {
                    if (userInfo.open_id_xcx == "" || userInfo.open_id_xcx == null)
                    {
                        // 更新公众号openid
                        AccountAction.updateUserInfoManager(sessionModel.unionid, sessionModel.openid,"");
                    }
                }
            }

            WechatJSCode2SessionDataModel sessionDataModel = new WechatJSCode2SessionDataModel();
            sessionDataModel.data = sessionModel;
            sessionDataModel.code = "200";
            sessionDataModel.msg = "成功";
            string sessionStr = Utils.toJSON(sessionDataModel);
            Utils.jsonBackManager(context, sessionStr);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}